<template>
  <div class="routes-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>航线管理</span>
          <el-button type="primary" @click="handleAddRoute">新增航线</el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="航线名称">
          <el-input v-model="searchForm.name" placeholder="请输入航线名称" />
        </el-form-item>
        <el-form-item label="状态" style="width: 200px">
          <el-select v-model="searchForm.is_active" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 航线列表 -->
      <el-table
        v-loading="loading"
        :data="routesData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          prop="name"
          label="航线名称"
          width="180"
          show-overflow-tooltip
        />

        <el-table-column
          prop="waypoint_count"
          label="航点数量"
          width="100"
          align="center"
        />

        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.is_active)">
              {{ getStatusLabel(scope.row.is_active) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ new Date(scope.row.created_at).toLocaleString("zh-CN") }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleViewRoute(scope.row)"
              >查看</el-button
            >
            <el-button size="small" type="primary" @click="handleEditRoute(scope.row)"
              >编辑</el-button
            >
    
            <el-button
              size="small"
              type="danger"
              @click="handleDeleteRoute(scope.row)"
              >删除</el-button
            >
            <el-button
              v-if="scope.row.is_active"
              size="small"
              type="primary"
              @click="handleToggleActive(scope.row)"
            >
              停用
            </el-button>
            <el-button
              v-else
              size="small"
              type="success"
              @click="handleToggleActive(scope.row)"
            >
              启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>



    <!-- 航线详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="航线详情" width="80%">
      <div class="route-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="航线名称">{{
            viewRoute.name
          }}</el-descriptions-item>

          <el-descriptions-item label="航点数量">{{
            viewRoute.waypoint_count
          }}</el-descriptions-item>
          <el-descriptions-item label="航线距离"
            >{{ viewRoute.distance || 0 }} km</el-descriptions-item
          >

          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(viewRoute.is_active)">
              {{ getStatusLabel(viewRoute.is_active) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            new Date(viewRoute.created_at).toLocaleString("zh-CN")
          }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{
            viewRoute.created_user?.name || "系统"
          }}</el-descriptions-item>
          <el-descriptions-item label="航线描述" :span="2">{{
            viewRoute.description || "无"
          }}</el-descriptions-item>
        </el-descriptions>

        <div
          class="waypoints-detail"
          v-if="viewRoute.waypoints && viewRoute.waypoints.length > 0"
        >
          <h3 style="margin-top: 20px">航点详情</h3>
          <el-table :data="viewRoute.waypoints" style="width: 100%">
            <el-table-column prop="index" label="序号" width="60" />
            <el-table-column prop="lat" label="纬度" />
            <el-table-column prop="lng" label="经度" />
            <el-table-column prop="alt" label="高度(m)" />
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑航线对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增航线' : '编辑航线'" width="80%">
      <el-form ref="routeFormRef" :model="routeForm" :rules="routeFormRules" label-width="100px">
        <el-form-item label="航线名称" prop="name">
          <el-input v-model="routeForm.name" placeholder="请输入航线名称" />
        </el-form-item>
        <el-form-item label="航线描述" prop="description">
          <el-input v-model="routeForm.description" type="textarea" :rows="3" placeholder="请输入航线描述" />
        </el-form-item>
        
        <!-- 航点列表 -->
        <el-form-item label="航点列表">
          <div class="waypoints-container">
            <div class="waypoints-tip">航线至少需要2个航点</div>
            <el-table :data="routeForm.waypoints" border style="width: 100%">
              <el-table-column prop="index" label="序号" width="60" />
              <el-table-column prop="lat" label="纬度" width="150">
                <template #default="scope">
                  <el-input v-model.number="scope.row.lat" type="number" step="0.000001" placeholder="纬度" />
                </template>
              </el-table-column>
              <el-table-column prop="lng" label="经度" width="150">
                <template #default="scope">
                  <el-input v-model.number="scope.row.lng" type="number" step="0.000001" placeholder="经度" />
                </template>
              </el-table-column>
              <el-table-column prop="alt" label="高度(m)" width="120">
                <template #default="scope">
                  <el-input v-model.number="scope.row.alt" type="number" step="1" placeholder="高度" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="danger" @click="deleteWaypoint(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="waypoint-actions">
              <el-button type="primary" @click="addWaypoint">添加航点</el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="航线距离">
          <el-input v-model="calculatedDistance" disabled placeholder="航线距离将自动计算" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRoute">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { flightRouteService } from "@/api/modules/flightRoute.js";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "FlightRoutes",
  data() {
    return {
      loading: false,
      dialogVisible: false,
      viewDialogVisible: false,
      dialogType: "add",
      editingId: null,
      routeFormRef: null,
      searchForm: {
        name: "",
        is_active: "",
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      routesData: [],

      viewRoute: {},
      selectedRoutes: [],
      statusOptions: [
        { label: "激活", value: 1 },
        { label: "未激活", value: 0 },
      ],
      routeForm: {
        name: "",
        description: "",
        waypoints: [],
      },
      routeFormRules: {
        name: [
          { required: true, message: '请输入航线名称', trigger: 'blur' },
          { min: 1, max: 100, message: '航线名称长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        waypoints: [
          {
            validator: (rule, value, callback) => {
              if (value.length < 2) {
                callback(new Error('航线至少需要2个航点'));
              } else {
                // 检查每个航点的坐标是否有效
                const invalidWaypoint = value.find(wp => 
                  !wp.lat || !wp.lng || 
                  isNaN(wp.lat) || isNaN(wp.lng) || isNaN(wp.alt) ||
                  wp.lat < -90 || wp.lat > 90 || wp.lng < -180 || wp.lng > 180
                );
                if (invalidWaypoint) {
                  callback(new Error('航点坐标无效，请检查所有航点'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'change'
          }
        ]
      },
      calculatedDistance: '0 km',
    };
  },
  mounted() {
      this.fetchRoutes();
    },
    
    watch: {
      // 监听航点变化，自动计算距离
      'routeForm.waypoints': {
        handler() {
          this.calculateDistance();
        },
        deep: true
      }
    },

  methods: {
      // 计算航线距离（简化版本，与后端保持一致的计算逻辑）
      calculateDistance() {
        const waypoints = this.routeForm.waypoints;
        if (waypoints.length < 2) {
          this.calculatedDistance = '0 km';
          return;
        }
        
        let totalDistance = 0;
        for (let i = 1; i < waypoints.length; i++) {
          const wp1 = waypoints[i-1];
          const wp2 = waypoints[i];
          
          if (wp1.lat && wp1.lng && wp2.lat && wp2.lng) {
            // 计算两点之间的欧氏距离
            const distance = Math.sqrt(
              Math.pow(wp2.lat - wp1.lat, 2) +
              Math.pow(wp2.lng - wp1.lng, 2) +
              Math.pow((wp2.alt || 0) - (wp1.alt || 0), 2)
            );
            totalDistance += distance;
          }
        }
        
        // 转换为千米并四舍五入到2位小数
        this.calculatedDistance = `${(totalDistance * 111.32).toFixed(2)} km`;
      },
      
      // 打开新增航线对话框
      handleAddRoute() {
        this.dialogType = 'add';
        this.editingId = null;
        this.resetForm();
        this.dialogVisible = true;
      },
      
      // 打开编辑航线对话框
      async handleEditRoute(row) {
        try {
          // 获取航线详情
          const response = await axios.get(`/api/routes/${row.id}`, {
            headers: {
              Authorization: `Bearer ${localStorage.getItem('token')}`
            }
          });
          
          if (response.data.code === 200 && response.data.data) {
            const route = response.data.data;
            this.dialogType = 'edit';
            this.editingId = row.id;
            
            // 填充表单数据
            this.routeForm = {
              name: route.name,
              description: route.description || '',
              waypoints: route.waypoints.map((wp, index) => ({
                index: index + 1,
                lat: wp.lat,
                lng: wp.lng,
                alt: wp.alt || 0
              }))
            };
            
            // 计算航线距离
            this.calculateDistance();
            this.dialogVisible = true;
          }
        } catch (error) {
          console.error('获取航线详情失败:', error);
          ElMessage.error('获取航线详情失败');
        }
      },
      
      // 重置表单
      resetForm() {
        if (this.routeFormRef) {
          this.$refs.routeFormRef.resetFields();
        }
        this.routeForm = {
          name: '',
          description: '',
          waypoints: [
            { index: 1, lat: null, lng: null, alt: 0 },
            { index: 2, lat: null, lng: null, alt: 0 }
          ]
        };
        this.calculatedDistance = '0 km';
      },
      
      // 添加航点
      addWaypoint() {
        this.routeForm.waypoints.push({
          index: this.routeForm.waypoints.length + 1,
          lat: null,
          lng: null,
          alt: 0
        });
        
        // 更新所有航点的索引
        this.routeForm.waypoints.forEach((wp, index) => {
          wp.index = index + 1;
        });
      },
      
      // 删除航点
      deleteWaypoint(index) {
        this.routeForm.waypoints.splice(index, 1);
        
        // 更新所有航点的索引
        this.routeForm.waypoints.forEach((wp, idx) => {
          wp.index = idx + 1;
        });
      },
      
      // 保存航线
      async handleSaveRoute() {
        try {
          // 验证表单
          await this.$refs.routeFormRef.validate();
          
          // 准备请求数据
          const requestData = {
            name: this.routeForm.name,
            description: this.routeForm.description,
            waypoints: this.routeForm.waypoints.map(wp => ({
              lat: wp.lat,
              lng: wp.lng,
              alt: wp.alt || 0
            }))
          };
          
          let response;
          
          if (this.dialogType === 'add') {
            // 新增航线
            response = await axios.post('/api/routes', requestData, {
              headers: {
                Authorization: `Bearer ${localStorage.getItem('token')}`
              }
            });
          } else {
            // 编辑航线（如果需要的话）
            response = await axios.put(`/api/routes/${this.editingId}`, requestData, {
              headers: {
                Authorization: `Bearer ${localStorage.getItem('token')}`
              }
            });
          }
          
          if (response.data.code === 200) {
            ElMessage.success(this.dialogType === 'add' ? '新增航线成功' : '更新航线成功');
            this.dialogVisible = false;
            this.fetchRoutes(); // 重新获取航线列表
          } else {
            throw new Error(response.data.message || '操作失败');
          }
        } catch (error) {
          console.error('保存航线失败:', error);
          ElMessage.error(error.message || '保存航线失败');
        }
      },
      
      // 获取航线列表
    async fetchRoutes() {
      this.loading = true;
      try {
        // 准备查询参数
        const params = {
          page: this.pagination.currentPage,
          page_size: this.pagination.pageSize,
          name: this.searchForm.name || undefined,
          is_active: this.searchForm.is_active === "" ? undefined : parseInt(this.searchForm.is_active),
        };

        // 发送API请求
        const response = await axios.get("/api/routes", {
          params,
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });

        // 处理响应数据
        if (response.data.code === 200 && response.data.data) {
          // 转换后端数据格式为前端需要的格式
          this.routesData = response.data.data.items.map((route) => ({
            ...route,
            waypoint_count: route.waypoints?.length || 0,
          }));

          // 更新分页信息
          this.pagination.total = response.data.data.total;
        } else {
          ElMessage.error("获取航线列表失败");
        }
      } catch (error) {
        console.error("获取航线列表失败:", error);
        ElMessage.error("获取航线列表失败");
      } finally {
        this.loading = false;
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchRoutes();
    },

    // 重置搜索
    resetSearch() {
      Object.keys(this.searchForm).forEach((key) => {
        this.searchForm[key] = "";
      });
      this.pagination.currentPage = 1;
      this.fetchRoutes();
    },

    // 分页处理
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.fetchRoutes();
    },

    handleCurrentChange(current) {
      this.pagination.currentPage = current;
      this.fetchRoutes();
    },

    // 选择行变化
    handleSelectionChange(selection) {
      this.selectedRoutes = selection;
    },



    // 查看航线详情
    async handleViewRoute(row) {
      try {
        const response = await axios.get(`/api/routes/${row.id}`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });

        if (response.data.code === 200 && response.data.data) {
          const route = response.data.data;
          this.viewRoute = {
            ...route,
            waypoint_count: route.waypoints?.length || 0,
            waypoints:
              route.waypoints?.map((wp, index) => ({
                index: index + 1,
                lat: wp.lat,
                lng: wp.lng,
                alt: wp.alt,
              })) || [],
          };
          this.viewDialogVisible = true;
        }
      } catch (error) {
        console.error("获取航线详情失败:", error);
        ElMessage.error("获取航线详情失败");
      }
    },

    // 删除航线
    handleDeleteRoute(row) {
      ElMessageBox.confirm(`确定要删除航线「${row.name}」吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            // 调用删除API
            const response = await axios.delete(`/api/routes/${row.id}`, {
              headers: {
                Authorization: `Bearer ${localStorage.getItem("token")}`,
              },
            });

            if (response.data.code === 200) {
              ElMessage.success("删除成功");
              this.fetchRoutes();
            } else {
              throw new Error(response.data.message || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            ElMessage.error(error.message || "删除失败");
          }
        })
        .catch(() => {
          // 取消删除
        });
    },

    // 切换激活状态
    async handleToggleActive(row) {
      const newStatus = row.is_active === 1 ? 0 : 1;
      const actionText = newStatus === 1 ? "启用" : "停用";
      
      ElMessageBox.confirm(`确定要${actionText}航线「${row.name}」吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const response = await axios.put(
              `/api/routes/${row.id}/toggle_active`,
              {},
              {
                headers: {
                  Authorization: `Bearer ${localStorage.getItem("token")}`,
                },
              }
            );

            if (response.data.code === 200) {
              ElMessage.success(`${actionText}成功`);
              this.fetchRoutes();
            } else {
              throw new Error(response.data.message || `${actionText}失败`);
            }
          } catch (error) {
            console.error(`${actionText}失败:`, error);
            ElMessage.error(error.message || `${actionText}失败`);
          }
        })
        .catch(() => {
          // 取消操作
        });
    },



    // 获取状态标签类型
    getStatusTagType(isActive) {
      return isActive === 1 ? "success" : "info";
    },

    // 获取状态标签
    getStatusLabel(isActive) {
      return isActive ? "激活" : "未激活";
    },
  },
};
</script>

<style scoped>
.routes-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.waypoints-container {
  margin-top: 10px;
}

.waypoints-tip {
  margin-top: 10px;
}

.route-detail {
  padding: 20px;
}

.waypoints-detail {
  margin-top: 20px;
}
</style>
